package org.net5ijy.commons.util;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import lombok.extern.slf4j.Slf4j;

/**
 * IOUtils类
 *
 * @author xuguofeng
 * @date 2020/7/13 11:12
 */
@Slf4j
public class IoUtils {

  public static void closeStream(Closeable stream) {
    if (stream != null) {
      try {
        stream.close();
      } catch (IOException e) {
        log.error(e.getMessage(), e);
      }
    }
  }

  /**
   * 从classpath或${user.dir}/config目录下加载配置文件输入流
   *
   * @param filename 文件名
   * @return 输入流
   */
  public static InputStream resourceInputStream(String filename) {
    InputStream in = null;
    try {
      in = IoUtils.class.getClassLoader().getResourceAsStream(filename);
      if (in == null) {
        in = new FileInputStream(System.getProperty("user.dir") +
            File.separator + "config" + File.separator + filename);
      }
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      // 关闭流
      closeStream(in);
    }
    return in;
  }
}
